"use client"

import { useState, useEffect, useRef } from "react"
import { Slider } from "@/components/ui/slider"
import { Button } from "@/components/ui/button"
import { PlayCircle, PauseCircle, SkipBack, SkipForward } from "lucide-react"
import { CustomGraphVisualization } from "./CustomGraphVisualization"

export default function DynamicGraphComponent({ 
  data, 
  timeSteps = 3 
}: { 
  data: any, 
  timeSteps?: number 
}) {
  const [currentTimeStep, setCurrentTimeStep] = useState(0)
  const [isPlaying, setIsPlaying] = useState(false)
  const [currentGraphData, setCurrentGraphData] = useState(data)
  const timerRef = useRef<NodeJS.Timeout | null>(null)

  // 在组件内部添加节点大小计算函数 - 确保节点非常小
  const calculateNodeSize = () => {
    return 2; // 固定使用非常小的值
  };

  // 模拟不同时间步的数据
  useEffect(() => {
    // 根据时间步生成不同的社区位置，模拟社区演化
    function generateTimeStepData(step: number) {
      const nodes = data.nodes.map((node: any) => {
        const communityId = parseInt(node.type.replace('社区', ''))
        
        // 根据时间步调整社区
        let newCommunityId = communityId
        if (step > 0 && Math.random() < 0.3) { // 30%的节点可能会改变社区
          newCommunityId = (communityId + step) % (Math.max(2, data.nodes.length / 5))
        }
        
        // 随机调整节点值，模拟动态变化
        const newValue = (node.value || 10) * (0.8 + Math.random() * 0.4); // 随机波动
        
        return {
          ...node,
          type: `社区${newCommunityId}`,
          color: ["#4285F4", "#EA4335", "#34A853", "#FBBC05", "#9C27B0"][newCommunityId % 5],
          value: newValue,
          // 使用固定的小尺寸
          size: 2
        }
      })
      
      // 创建新的 cosmographData
      const newCosmographData = {
        ...data.cosmographData,
        nodes: nodes.map((node: any) => ({
          ...node,
          size: 2, // 固定为非常小的值
          color: node.color
        }))
      }
      
      return {
        ...data,
        nodes,
        cosmographData: newCosmographData
      }
    }
    
    setCurrentGraphData(generateTimeStepData(currentTimeStep))
  }, [currentTimeStep, data])
  
  // 自动播放
  useEffect(() => {
    if (isPlaying) {
      timerRef.current = setInterval(() => {
        setCurrentTimeStep(prev => {
          const next = prev + 1
          if (next >= timeSteps) {
            setIsPlaying(false)
            return 0
          }
          return next
        })
      }, 2000)
    } else if (timerRef.current) {
      clearInterval(timerRef.current)
    }
    
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current)
      }
    }
  }, [isPlaying, timeSteps])
  
  const handlePlayPause = () => {
    setIsPlaying(!isPlaying)
  }
  
  const handlePrevious = () => {
    setIsPlaying(false)
    setCurrentTimeStep(prev => (prev > 0 ? prev - 1 : 0))
  }
  
  const handleNext = () => {
    setIsPlaying(false)
    setCurrentTimeStep(prev => (prev < timeSteps - 1 ? prev + 1 : prev))
  }
  
  const handleSliderChange = (value: number[]) => {
    setIsPlaying(false)
    setCurrentTimeStep(value[0])
  }
  
  return (
    <div className="space-y-6">
      <div className="h-[500px] rounded-lg border overflow-hidden">
        {currentGraphData && <CustomGraphVisualization data={currentGraphData} />}
      </div>
      
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div className="text-sm font-medium">
            时间步骤: {currentTimeStep + 1} / {timeSteps}
          </div>
          <div className="flex items-center space-x-2">
            <Button
              variant="outline"
              size="icon"
              onClick={handlePrevious}
              disabled={currentTimeStep === 0}
            >
              <SkipBack className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="icon"
              onClick={handlePlayPause}
            >
              {isPlaying ? (
                <PauseCircle className="h-4 w-4" />
              ) : (
                <PlayCircle className="h-4 w-4" />
              )}
            </Button>
            <Button
              variant="outline"
              size="icon"
              onClick={handleNext}
              disabled={currentTimeStep === timeSteps - 1}
            >
              <SkipForward className="h-4 w-4" />
            </Button>
          </div>
        </div>
        
        <Slider
          value={[currentTimeStep]}
          max={timeSteps - 1}
          step={1}
          onValueChange={handleSliderChange}
        />
      </div>
    </div>
  )
} 